(function() {
    angular.module('app').factory('popupService', popupService);

    popupService.$inject = ['util', '$rootScope'];

    function popupService(util, $rootScope) {
        return {
            historyOnShop: _historyOnShop,
            historyOnBrand: _historyOnBrand,
            historyOnProduct: _historyOnProduct,
            historyNoHTTP: _historyNoHTTP
        }

        function _historyOnShop(json, container, option, dim) {
            if (container) {
                var myChart = echarts.init(container);
                myChart.showLoading();
            }


            util.$get(json).then(function(resp) {
                var arr = resp.value[dim].split(';');
                angular.forEach(arr, function(item, index) {
                    option.xAxis.data.push(item.split('=')[0]);
                    option.series[0].data.push(item.split('=')[1]);
                });





                if (container) {
                    myChart.setOption(option);
                    myChart.hideLoading();
                } else {
                    $rootScope.$emit('echart_draw_line_EV', option, 'pop_line');
                }


            }, function(err) {
                option.title.text = "暂无数据";

                if (container) {
                    myChart.setOption(option);
                    myChart.hideLoading();
                } else {
                    $rootScope.$emit('echart_draw_line_EV', option, 'pop_line');
                }

            });
        }

        function _historyOnBrand(json, container, option, dim) {
            if (container) {
                var myChart = echarts.init(container);
                myChart.showLoading();
            }

            util.$get(json).then(function(resp) {

                angular.forEach(resp.value, function(item) {


                    option.xAxis.data.push(item.date.split(' ')[0]);

                    if (dim == 'avgPrice') {

                        var avgPrice = item['sellAmount'] == 0 ? 0 : item['sellMoney'] / item['sellAmount'];
                        // console.log(avgPrice.toFixed(2));
                        option.series[0].data.push(avgPrice);
                    } else {
                        option.series[0].data.push(item[dim]);
                    }


                });

                if (container) {
                    myChart.setOption(option);
                    myChart.hideLoading();
                } else {
                    $rootScope.$emit('echart_draw_line_EV', option, 'pop_line');
                }

            }, function(err) {
                option.title.text = "暂无数据";
                if (container) {
                    myChart.setOption(option);
                    myChart.hideLoading();
                } else {
                    $rootScope.$emit('echart_draw_line_EV', option, 'pop_line');
                }
            });
        }

        function _historyOnProduct(json, container, option, dim) {
            if (container) {
                var myChart = echarts.init(container);
                myChart.showLoading();
            }

            util.$get(json).then(function(resp) {

                angular.forEach(resp.value, function(item) {


                    option.xAxis.data.push(item.date.split(' ')[0]);
                    option.series[0].data.push(item[dim]);
                });
                if (container) {
                    myChart.setOption(option);
                    myChart.hideLoading();
                } else {
                    $rootScope.$emit('echart_draw_line_EV', option, 'pop_line');
                }

            }, function(err) {
                option.title.text = "暂无数据";
                if (container) {
                    myChart.setOption(option);
                    myChart.hideLoading();
                } else {
                    $rootScope.$emit('echart_draw_line_EV', option, 'pop_line');
                }
            });
        }

        function _historyNoHTTP(data, container, option, dim) {
            if (container) {
                var myChart = echarts.init(container);
                myChart.showLoading();
            }

            var json = util.historyFormat(data[dim]);


            option.xAxis.data = json.x;
            option.series[0].data = json.y;
            if (container) {
                myChart.setOption(option);
                myChart.hideLoading();
            } else {
                $rootScope.$emit('echart_draw_line_EV', option, 'pop_line');
            }
        }


    }

    angular.module('app').directive('jqPopup', ['util', 'popupService', '$rootScope', '$timeout', function(util, popupService, $rootScope, $timeout) {
        return {
            restrict: 'A',
            scope: {
                popupConfig: '<', //data
                popupType: '<', //popup type
                popupDim: '<', //popup dim ->names[]
                popupMethod: '<'
            },
            css: 'app/directives/jq.popup/jq.popup.directive.css',
            link: function(scope, element, iAttrs) {
                // console.log(iAttrs);
                // type
                // dim

                var names = {
                    sellMoney: '销售额',
                    historySellMoney: '销售额',
                    sellAmount: '销售量',
                    historySellAmount: '销售量',
                    avgPrice: '成交均价',
                    price: '成交均价',

                    historySellAmount: '销售量',
                    historySellMoney: '销售额',
                    historyFavCount: '收藏数',
                    historyView: '流量指数'
                };

                var option = {
                    title: {
                        text: '',
                        subtext: '',
                        x: 'center'
                    },
                    toolbox: {
                        show: true,
                        top: 0,
                        feature: {
                            dataZoom: {
                                yAxisIndex: 'none'
                            },
                            dataView: { readOnly: false },
                            magicType: { type: ['line', 'bar'] },
                            restore: {},
                            saveAsImage: {}
                        }
                    },
                    tooltip: {
                        trigger: 'axis',
                        axisPointer: { // 坐标轴指示器，坐标轴触发有效
                            type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
                        },
                        formatter: function(params) {

                            var str = '<div style = "text-align: left;">' + params[0].name + '</div>';

                            for (var i = 0; i < params.length; i++) {
                                str += '<div style = "text-align: left;padding-left:10px;">' + params[i].seriesName + ' : ' + util.bigNumFormat(params[i].data) + '</div>';
                            }

                            return str;
                        }
                    },

                    legend: {
                        data: ['总和销售额'],
                        x: 'right'
                    },
                    xAxis: {
                        data: [],
                        axisLabel: {
                            show: true
                        }
                    },
                    grid: {
                        top: '40px',
                        left: '1%',
                        right: '40px',
                        bottom: '4px',
                        containLabel: true
                    },
                    yAxis: [{
                        type: 'value',
                        axisLabel: {
                            formatter: function(value, index) {
                                var len = String(value).length;

                                if (value < 10000) {
                                    return value;
                                }

                                switch (len) {
                                    case 5:
                                        return (value / 10000).toFixed(2) + '万';
                                    case 6:
                                        return (value / 10000).toFixed(2) + '万';
                                    case 7:
                                        return (value / 10000).toFixed(2) + '万';
                                    case 8:
                                        return (value / 10000).toFixed(2) + '万';
                                    case 9:
                                        return (value / 100000000).toFixed(2) + '亿';
                                    case 10:
                                        return (value / 100000000).toFixed(2) + '亿';
                                    case 11:
                                        return (value / 100000000).toFixed(2) + '亿';
                                    case 12:
                                        return (value / 100000000).toFixed(2) + '亿';
                                }

                                return value;
                            }
                        }
                    }],
                    series: [{
                        name: names[scope.popupDim],
                        type: 'line',
                        data: [],
                        markPoint: {
                            data: [
                                { type: 'max', name: '最大值' },
                                { type: 'min', name: '最小值' }
                            ]
                        },
                        markLine: {
                            data: [
                                { type: 'average', name: '平均值' }
                            ]
                        }
                    }]
                };


                scope.getHttpType = getHttpType;

                function getHttpType(box) {
                    // var 
                    switch (scope.popupType) {
                        case 'shop':
                            var data = {
                                url: '/marketconditions/shop/getShopByUid.htm',
                                data: {
                                    uid: scope.popupConfig.userId
                                }
                            }
                            popupService.historyOnShop(data, box, angular.copy(option), scope.popupDim);
                            break;
                        case 'brand':
                            var data = {
                                url: '/marketconditions/brand/getBrandIndex.htm',
                                data: {
                                    brand: scope.popupConfig.brandName

                                }
                            }
                            popupService.historyOnBrand(data, box, angular.copy(option), scope.popupDim);
                            break;
                        case 'product':
                            var data = {
                                url: '/marketconditions/product/getHistoryProduct.htm',
                                data: {
                                    numberId: scope.popupConfig.numberId,
                                    uid: scope.popupConfig.uid

                                }
                            }
                            popupService.historyOnProduct(data, box, angular.copy(option), scope.popupDim);
                            break;
                        case 'noHTTP':
                            var data = scope.popupConfig;

                            popupService.historyNoHTTP(data, box, angular.copy(option), scope.popupDim);
                            break;
                        default:
                            break;
                    }

                    //$rootScope.$emit('echart_draw_line_EV',,'popover_line');
                }



                if (document.body.clientWidth > 600) { //pc
                    $(element).on('click', function() {
                        getHttpType();
                    });
                    $rootScope.popoverEnable = true;

                } else { //mobile
                    $rootScope.popoverEnable = false;
                    var fun = function() {
                        getHttpType($('#jq-modal-box .modal-content')[0]);
                    };
                    $(element).on('click', function() {
                        $rootScope.$emit('JQ_MODAL_EV', fun);
                    });
                };

            }
        }
    }]);
})();
